<?php

namespace app\zyhsapi\model;

use app\chat\LiveMessage;
use app\common\cachemodel\Recode;
use app\common\cachemodel\zl8\Zl8UserChatReservationRecord;
use app\common\lib\Util;
use think\Db;
use XznsTools\cache\zyhs\CacheManageZyhs;

class ZyhsConsultChatRecordDetails extends BaseCacheZyhs
{
    protected $table = 'good_wechat.zyhs_consult_chat_record_details';

    protected $cacheModel = 'voice_consult.chat_details';

    public $interceptTips = '安全巡查已介入，为保障你的权益和隐私，请遵守平台规则';

    /**
     * 获取列表数据
     * @param int $chatId
     * @param int $limit
     * @param int $maxId
     * @return array
     * @throws \Exception
     */
    public function getPageDatas(int $chatId, int $limit, int $maxId = 0)
    {
        if ($chatId === 0)
        {
            return [
                'total' => 0,
                'surplus_num' => 0,
                'data' => [],
            ];
        }

        $idsData = CacheManageZyhs::getInstance()
            ->setCacheConfig($this->cacheModel, $chatId)
            ->setPage(-1)
            ->setSort('desc')
            ->getListPageDataIds(function ($isCache = true, $sortType = 'desc') use ($chatId)
            {
                try
                {
                    $data = $this->where(['chat_id' => $chatId])->order("id {$sortType}")->column('id');

                    $resData = [];
                    foreach ($data as $id)
                    {
                        $resData[$id] = ['id' => $id];
                    }

                    return $resData;
                }
                catch (\Exception $e)
                {
                    return [];
                }
            }, 'id', 0);

        arsort($idsData['data']);
        $allIds = array_keys($idsData['data']);
        $ids = [];
        $surplusNum = 0;
        foreach ($allIds as $idItem)
        {
            if ($maxId > 0 && $idItem >= $maxId) continue;

            if (count($ids) >= $limit)
            {
                $surplusNum++;
            } else
            {
                $ids[] = $idItem;
            }
        }
        $dataList = $this->batchGetInfoByIds($ids);
        asort($ids);

        $resDataList = [];
        foreach ($ids as $idItem)
        {
            if (isset($dataList[$idItem]))
            {
                $resDataList[] = $dataList[$idItem];
            }
        }

        $resData = [
            'total' => count($allIds),
            'surplus_num' => $surplusNum,
            'data' => $resDataList,
        ];

        return $resData;
    }

    /**
     * 咨询对话写入数据
     */
    public function SaveData(int $chatId, array $datas)
    {
        try
        {
            if (isset($datas['extend']) && is_array($datas['extend']))
            {
                $datas['extend'] = json_encode($datas['extend'], JSON_UNESCAPED_UNICODE);
            }
            $id = $this->insertGetId($datas);
            $datas['id'] = (int)$id;
            // list ID添加
            $this->listDataAdd($chatId, [$datas['id'] => $datas['id']]);
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return [];
        }

        if (isset($datas['extend']))
        {
            $datas['extend'] = $datas['extend'] ? json_decode($datas['extend'], true) : [];
        }

        return $datas;
    }

    public function UpdateData(int $id, array $data)
    {
        try
        {
            if (isset($data['extend']) && is_array($data['extend']))
            {
                $data['extend'] = json_encode($data['extend'], JSON_UNESCAPED_UNICODE);
            }
            $data['update_time'] = time();

            $this->where(['id' => $id])->update($data);

            CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel, $id)->setCacheTime(3)->setCache($data);
            return true;
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return false;
        }
    }

    /**
     * 数据 返回样式重组
     * @param array $dataList
     * @param array $astrInfo 占星师信息
     * @param array $userInfo 用户信息
     * @param null $delayComment 待评论信息
     * @param int $appType 1=>准有好事 2=>准了APP
     * @return array
     * @throws \Exception
     */
    public function userDataListResert(array $dataList, array $astrInfo, array $userInfo, int $appType = 1, &$delayComment = null)
    {
        $resData = [];
        $lastTime = 0;
        if ($appType === 1)
        {   // 准有好事
            $astrInfoShow = Util::CheckAppVersion('1.2.0') !== '小';
            $recodeModel = new ZyhsRecode();
        } else
        {   // 准了APP
            $astrInfoShow = true;
            $recodeModel = new Recode();
        }
        $now0Time = strtotime(date('Y-m-d')); // 今日0点时间
        foreach ($dataList as $k => $dataItem)
        {
            $createTime = '';
            if ($dataItem['create_time'] - $lastTime > 300)
            {
                $createTime = $this->timeConvert($dataItem['create_time'], $now0Time);
            }
            // $dataItem['type']  1=>APP消息 2=>用户发送消息
            $avatar = $dataItem['type'] === 1 ? $astrInfo['avatar'] : $userInfo['avatar'];
            $consultInfo = null;
            $btnInfo = null;
            $recodeItemInfo = null;
            $appointmentInfo = null;
            $pluginsInfo = null;
            $contentType = 1;
            $msgDes = $dataItem['title'];
            $content = '';
            switch ($dataItem['data_type'])
            {
                case 1: // 普通消息
                case 12: // 默认回复
                    $content = $dataItem['content'];
                    break;
                case 2: // 图片
                    $content = $dataItem['content'];
                    $contentType = 2;
                    break;
                case 3: // 语音咨询消息
                    $msgDes = '连线咨询';
                    $content = '';
                    if ($dataItem['extend']['rtc_data']['rtc_id'] > 0)
                    {
                        $rtcInfo = (new ZyhsConsultChatRtcRecord())->getInfoById($dataItem['extend']['rtc_data']['rtc_id']);
                        $link = "alert_consult_question?id={$dataItem['id']}&need_auth=2";
                        switch ($rtcInfo['status'])
                        {
                            case 1:
                                $consultInfo = [
                                    'status' => 1, // 1=>申请连线中 2=>连接中 3=>连线中 4=>咨询结束
                                    'tip' => '正在发起语音咨询',
                                    'target' => 'local',
                                    'link' => $link,
                                ];
                                break;
                            case 2:
                                $consultInfo = [
                                    'status' => 2, // 1=>申请连线中 2=>连接中 3=>连线中 4=>咨询结束
                                    'tip' => '正在接通中',
                                    'target' => 'local',
                                    'link' => $link,
                                ];
                                break;
                            case 3:
                                $consultInfo = [
                                    'status' => 3, // 1=>申请连线中 2=>连接中 3=>连线中 4=>咨询结束
                                    'tip' => '连线咨询中',
                                    'target' => 'local',
                                    'link' => $link,
                                ];
                                break;
                            case 4:
                                $durationTime = Util::secondToMinute($rtcInfo['duration']);
                                $consultInfo = [
                                    'status' => 4, // 1=>申请连线中 2=>连接中 3=>连线中 4=>咨询结束
                                    'tip' => "连线时长 {$durationTime}，消耗{$rtcInfo['coin']}准币",
                                    'target' => 'local',
                                    'link' => "rtc_consult_detail?id={$dataItem['id']}&need_auth=2",
                                ];
                                if (time() - $rtcInfo['end_time'] > 86400 || $rtcInfo['is_comment'] || $rtcInfo['duration'] < 300)
                                {   // 1天后 不显示 评价
                                    $delayComment = null;
                                } else
                                {
                                    $delayComment = [
                                        'id' => $dataItem['id'],
                                        'duration' => $rtcInfo['duration'],
                                        'coin' => $rtcInfo['coin'],
                                        'avatar' => $astrInfo['avatar'] ?? null,
                                        'name' => $astrInfo['nickname'] ?? null,
                                    ];
                                }
                                break;
                            case 5:
                                $consultInfo = [
                                    'status' => 4, // 1=>申请连线中 2=>连接中 3=>连线中 4=>咨询结束
                                    'tip' => '故障挂断',
                                    'target' => 'local',
                                    'link' => 'empty',
                                ];
                                break;
                            case 6:
                                $consultInfo = [
                                    'status' => 4, // 1=>申请连线中 2=>连接中 3=>连线中 4=>咨询结束
                                    'tip' => $rtcInfo['type'] === 2 ? '咨询师不便接听，稍后重试' : '连线已取消', // 挂断用户  1=>用户   2=>咨询师
                                    'target' => 'local',
                                    'link' => 'empty',
                                ];
                                break;
                            case 7:
                                $consultInfo = [
                                    'status' => 4, // 1=>申请连线中 2=>连接中 3=>连线中 4=>咨询结束
                                    'tip' => '连线已取消', // 挂断用户  1=>用户   2=>咨询师
                                    'target' => 'local',
                                    'link' => 'empty',
                                ];
                                break;
                            default:
                        }
                    } else
                    {
                        switch ($dataItem['extend']['rtc_data']['status'])  // 1=>申请中待接听  2=>咨询师未响应  3=>咨询师拒绝  4=>连线已取消 5=>咨询师忙线中
                        {
                            case 1: // 申请中待接听
                                $consultInfo = [
                                    'status' => 1, // 1=>申请连线中 2=>连线中 3=>咨询结束
                                    'tip' => '正在发起语音咨询',
                                    'target' => 'local',
                                    'link' => "alert_consult_question?id={$dataItem['id']}&need_auth=2",
                                ];
                                break;
                            case 2: // 咨询师未响应
                                $consultInfo = [
                                    'status' => 4, // 1=>申请连线中 2=>连线中 3=>咨询结束
                                    'tip' => '咨询师未响应',
                                    'target' => 'local',
                                    'link' => "alert_consult_question?id=0&need_auth=2",
                                ];
                                break;
                            case 3: // 咨询师拒绝
                                $consultInfo = [
                                    'status' => 4, // 1=>申请连线中 2=>连线中 3=>咨询结束
                                    'tip' => '咨询师不便接听，稍后重试',
                                    'target' => 'local',
                                    'link' => "alert_consult_question?id=0&need_auth=2",
                                ];
                                break;
                            case 4: // 连线已取消
                                $consultInfo = [
                                    'status' => 4, // 1=>申请连线中 2=>连线中 3=>咨询结束
                                    'tip' => '连线已取消',
                                    'target' => 'local',
                                    'link' => "alert_consult_question?id=0&need_auth=2",
                                ];
                                break;
                            case 5: // 咨询师忙线中
                                $consultInfo = [
                                    'status' => 4, // 1=>申请连线中 2=>连线中 3=>咨询结束
                                    'tip' => '忙线中',
                                    'target' => 'local',
                                    'link' => "alert_consult_question?id=0&need_auth=2",
                                ];
                                break;
                        }
                    }
                    break;
                case 4: // 咨询问题
                    $msgDes = '我的问题已提交 —— 问题咨询';
                    $content = $dataItem['content'];
                    break;
                case 5: // 咨询问题答案
                    $msgDes = '问题已收到';
                    $content = $dataItem['content'];
                    $btnInfo = [
                        'name' => '语言连线咨询',
                        'target' => 'local',
                        'link' => "alert_consult_question?id=0&need_auth=2",
                        'type' => 1,
                    ];
                    break;
                case 6: // 问答问题回复
                    $qid = $dataItem['extend']['qa_data']['qid'];
                    $msgDes = '悬赏问题已回复';
                    $content = '你好，你的疑惑已给出回复，点击下方即可查看，有什么问题可以追问我继续帮你进行解答～';
                    if ($appType === 1)
                    {
                        $btnInfo = [
                            'name' => '查看回复',
                            'target' => 'local',
                            'link' => "question_detail?qid={$qid}&need_auth=0",
                            'type' => 2,
                        ];
                    } else
                    {
                        $pluginsInfo = [
                            'icon' => '/test/consult_chat/plugins/qa_icon.png',
                            'list' => ['悬赏问答', '点击查看'],
                            'target' => 'local',
                            'link' => "question_detail?qid={$qid}&need_auth=0",
                        ];
                    }
                    break;
                case 7: // 问答追问问题回复
                    $qid = $dataItem['extend']['qa_data']['qid'];
                    $msgDes = '悬赏追问已回复';
                    $content = '你好，你的疑惑已给出回复，点击下方即可查看，有什么问题可以追问我继续帮你进行解答～';
                    if ($appType === 1)
                    {
                        $btnInfo = [
                            'name' => '查看回复',
                            'target' => 'local',
                            'link' => "question_detail?qid={$qid}&need_auth=0",
                            'type' => 2,
                        ];
                    } else
                    {
                        $pluginsInfo = [
                            'icon' => '/test/consult_chat/plugins/qa_icon.png',
                            'list' => ['悬赏问答', '点击查看'],
                            'target' => 'local',
                            'link' => "question_detail?qid={$qid}&need_auth=0",
                        ];
                    }
                    break;
                case 8: // 发送 档案问题
                    $msgDes = '星盘';
                    $content = '';
                    if ($astrInfoShow)
                    {   // 支持 显示 星盘信息
                        $recodeExtend = $dataItem['extend']['recode_info'];
                        $ridItem = (int)($recodeExtend['rid'] ?? 0);
                        $list = [
                            "{$recodeExtend['year']}.{$recodeExtend['month']}.{$recodeExtend['day']}",
                            "日{$recodeExtend['sun']} 月{$recodeExtend['moon']} 升{$recodeExtend['asc']}",
                        ];
                        $recodeItem = $recodeModel->getInfoById($ridItem);
                        if ($recodeItem && $recodeItem['status'] == 1)
                        {
                            $target = 'local';
                            $link = "astrolable?rid={$ridItem}&need_auth=1";
                        } else
                        {
                            $target = 'toast';
                            $link = '档案已删除！';
                        }
                        $recodeItemInfo = [
                            'rid' => $ridItem,
                            'list' => $list,
                            'target' => $target,
                            'link' => $link,
                            'icon' => '/zyhsapp/astro_icon.png',
                        ];
                    } else
                    {
                        $content = '当前版本不支持显示星盘信息，请升级应用';
                    }
                    break;
                case 9://预约
                    //获取预约状态和预约时间
                    $msgDes = $dataItem['extend']['reservation_info']['title'];
                    $content = $dataItem['extend']['reservation_info']['content'];
                    $appointmentInfo = [
                        'icon' => '/zyhsapp/reservation.png',
                        'list' => [
                            '预约时间',
                            $dataItem['extend']['reservation_info']['time_des'],
                        ],
                    ];
                    break;
                case 10: // 求打赏礼物
                    $pluginsInfo = [
                        'icon' => '/test/consult_chat/plugins/gift_icon.png',
                        'list' => ['礼物', '点击打赏'],
                        'target' => 'local',
                        'link' => 'consult_pop_gift?need_auth=2',
                    ];
                    $content = '如果你对我的服务满意，可以对我进行打赏，非常感谢！';
                    break;
                case 11: // 用户打赏礼物
                    $msgDes = '礼物打赏';
                    $pluginsInfo = [
                        'icon' => '/test/consult_chat/plugins/gift_icon.png',
                        'list' => ['礼物', sprintf('%sx%d', $dataItem['extend']['gift_data']['gift_name'], $dataItem['extend']['gift_data']['num'])],
                        'target' => 'local',
                        'link' => 'empty',
                    ];
                    $content = '给你一些奖励';
                    break;
                default:
            }
            $data = [
                'id' => $dataItem['id'],
                'type' => $dataItem['type'] === 1 ? 2 : 1,
                'time_des' => $createTime,
                'time' => 0,
                'avatar' => $avatar,
                'msg_des' => $msgDes,
                'tags' => $dataItem['extend']['tags'] ?? [],
                'consult_info' => $consultInfo ?? null,
                'content' => $content,
                'content_type' => $contentType,
                'btn_info' => $btnInfo ?? null,
                'astr_info' => $recodeItemInfo ?? null,
                'appointment_info' => $appointmentInfo ?? null,
                'plugins_info' => $pluginsInfo ?? null,
                'intercept_tips' => !empty($dataItem['extend']['intercept_tips']) ? $this->interceptTips : '',
            ];

            // 更新最后发送时间
            $lastTime = $dataItem['create_time'];
            $resData[] = $data;
        }

        return $resData;
    }

    /**
     * 数据 返回样式重组
     * @param array $dataList
     * @param array $astrInfo 占星师信息
     * @param array $userInfo 用户信息
     * @param int $appType 1=>准有好事 2=>准了APP
     * @return array
     * @throws \Exception
     */
    public function astrDataListResert(array $dataList, array $astrInfo, array $userInfo, int $appType = 1)
    {
        $resData = [];
        $lastTime = 0;
        $now0Time = strtotime(date('Y-m-d')); // 今日0点时间
        $nowTime = time();
        $userDesStr = '';
        if ($appType === 1)
        {   // 准有好事
            $recodeModel = new ZyhsRecode();
        } else
        {
            $recodeModel = new Recode();
        }
        $utilModel = new Util();
        if ($userInfo && $userInfo['rid'])
        {
            $recode = $recodeModel->getInfoById($userInfo['rid']);
            if ($recode)
            {
                $sexTxt = [
                    1 => '男生',
                    2 => '女生',
                ];
                $age = Util::getAgeByBirth($recode['year'], $recode['month'], $recode['day'], 2);
                $sex = $sexTxt[$recode['type']] ?? '未知';
                $userDesStr = '日' . $utilModel->recodeAstroShorthand($recode['sun']) . '月' . $utilModel->recodeAstroShorthand($recode['moon']) . '升' . $utilModel->recodeAstroShorthand($recode['asc']) . "·{$age}周岁·{$sex}";
            }
        }
        $consultChatRtcRecordModel = new ZyhsConsultChatRtcRecord();
        foreach ($dataList as $k => $dataItem)
        {
            //1=>APP消息(咨询师消息) 2=>用户发送消息  3=>系统消息
            if ($dataItem['type'] === 3)
            {
                //咨询师端不展示预约的系统类型消息
                break;
            }
            $createTime = '';
            if ($dataItem['create_time'] - $lastTime > 300)
            {
                $createTime = $this->timeConvert($dataItem['create_time'], $now0Time);
            }
            // $dataItem['type']  1=>APP消息 2=>用户发送消息
            $avatar = $dataItem['type'] === 1 ? $astrInfo['avatar'] : $userInfo['avatar'];
            $checkTime = 0;
            if ($dataItem['type'] === 1 && $nowTime - $dataItem['create_time'] < 30)
            {   // 咨询师消息
                $checkTime = 30 - ($nowTime - $dataItem['create_time']);
            }
            $msgDes = $dataItem['title'];
            $userDes = '';
            $btnInfo = null;
            $recodeItemInfo = null;
            $consultInfo = null;
            $appointmentInfo = null;
            $pluginsInfo = null;
            $contentType = 1;
            $serverSuc = 0;
            $isComment = 0;
            switch ($dataItem['data_type'])
            {
                case 1:
                case 12:
                    $content = $dataItem['content'];
                    break;
                case 2:
                    $content = $dataItem['content'];
                    $contentType = 2;
                    break;
                case 3:
                    $msgDes = '连线咨询';
                    $content = '';
                    if ($dataItem['extend']['rtc_data']['rtc_id'] > 0)
                    {
                        $rtcInfo = $consultChatRtcRecordModel->getInfoById($dataItem['extend']['rtc_data']['rtc_id']);
                        switch ($rtcInfo['status'])
                        {
                            case 2:
                                $consultInfo = [
                                    'status' => 2, // 1=>申请连线中 2=>连接中 3=>连线中 4=>咨询结束
                                    'tip' => '正在申请连线咨询',
                                    'target' => 'local',
                                    'link' => 'empty',
                                ];
                                $btnInfo = [
                                    [
                                        'name' => '连接中',
                                        'type' => 5,
                                        'id' => $dataItem['id'],
                                        'target' => '',
                                        'link' => '',
                                    ],
                                ];
                                break;
                            case 3:
                                $consultInfo = [
                                    'status' => 3, // 1=>申请连线中 2=>连接中 3=>连线中 4=>咨询结束
                                    'tip' => '连线咨询中',
                                    'target' => 'local',
                                    'link' => 'empty',
                                ];
                                break;
                            case 4: // 4=>连麦结束
                                $durationTime = Util::secondToMinute($rtcInfo['duration']);
                                $astrEarning = (float)$rtcInfo['astr_earning'];
                                $consultInfo = [
                                    'status' => 4, // 1=>申请连线中 2=>连接中 3=>连线中 4=>咨询结束
                                    'tip' => "连线时长 {$durationTime}，收益{$astrEarning}元",
                                    'target' => 'local',
                                    'link' => 'empty',
                                ];
                                $serverSuc = 1;
                                $isComment = !empty($dataItem['extend']['rtc_data']['is_comment']) ? 1 : 0;
                                $btnInfo = [
                                    [
                                        'name' => '查看记录',
                                        'type' => 4,
                                        'id' => $dataItem['id'],
                                        'target' => '',
                                        'link' => '',
                                    ],
                                ];
                                break;
                            case 5: // 5=>故障挂断
                                $consultInfo = [
                                    'status' => 4, // 1=>申请连线中 2=>连接中 3=>连线中 4=>咨询结束
                                    'tip' => '故障挂断',
                                    'target' => 'local',
                                    'link' => 'empty',
                                ];
                                break;
                            case 6: // 6=>取消连麦（连接中挂断
                                $consultInfo = [
                                    'status' => 4, // 1=>申请连线中 2=>连接中 3=>连线中 4=>咨询结束
                                    'tip' => '连线已取消',
                                    'target' => 'local',
                                    'link' => 'empty',
                                ];
                                break;
                            case 7: // 6=>取消连麦（连接中挂断
                                $consultInfo = [
                                    'status' => 4, // 1=>申请连线中 2=>连接中 3=>连线中 4=>咨询结束
                                    'tip' => '接通失败',
                                    'target' => 'local',
                                    'link' => 'empty',
                                ];
                                break;
                        }
                    } else
                    {
                        switch ($dataItem['extend']['rtc_data']['status'])  // 1=>申请中待接听  2=>咨询师未响应  3=>咨询师拒绝  4=>连线已取消 5=>咨询师忙线中
                        {
                            case 1: // 申请中待接听
                                $consultInfo = [
                                    'status' => 1, // 1=>申请连线中 2=>连线中 3=>咨询结束
                                    'tip' => '正在申请连线咨询',
                                    'target' => 'local',
                                    'link' => 'empty',
                                ];
                                $btnInfo = [
                                    [
                                        'name' => '接受连线',
                                        'type' => 2,
                                        'id' => $dataItem['id'],
                                        'target' => '',
                                        'link' => '',
                                    ], [
                                        'name' => '拒绝',
                                        'type' => 3,
                                        'id' => $dataItem['id'],
                                        'target' => '',
                                        'link' => '',
                                    ],
                                ];
                                break;
                            case 2: // 咨询师未响应
                                $consultInfo = [
                                    'status' => 4, // 1=>申请连线中 2=>连线中 3=>咨询结束
                                    'tip' => '咨询师未响应',
                                    'target' => 'local',
                                    'link' => 'empty',
                                ];
                                break;
                            case 3: // 咨询师拒绝
                                $consultInfo = [
                                    'status' => 4, // 1=>申请连线中 2=>连线中 3=>咨询结束
                                    'tip' => '咨询师拒绝连线',
                                    'target' => 'local',
                                    'link' => 'empty',
                                ];
                                break;
                            case 4: // 连线已取消
                                $consultInfo = [
                                    'status' => 4, // 1=>申请连线中 2=>连线中 3=>咨询结束
                                    'tip' => '连线已取消',
                                    'target' => 'local',
                                    'link' => 'empty',
                                ];
                                break;
                            case 5: // 咨询师忙线中
                                $consultInfo = [
                                    'status' => 4, // 1=>申请连线中 2=>连线中 3=>咨询结束
                                    'tip' => '忙线中',
                                    'target' => 'local',
                                    'link' => 'empty',
                                ];
                                break;
                        }
                    }
                    break;
                case 4: // 咨询问题
                    $msgDes = '我的问题已提交';
                    $content = $dataItem['content'];
                    $userDes = $userDesStr;
                    if (!isset($dataItem['extend']['answer_id']))
                    {
                        $btnInfo[] = [
                            'name' => '回复问题',
                            'type' => 1,
                            'id' => $dataItem['id'],
                            'target' => '',
                            'link' => '',
                        ];
                    }
                    break;
                case 5: // 咨询问题答案
                    $msgDes = '';
                    $content = $dataItem['content'];
                    break;
                case 6: // 问答问题回复
                    $taskId = $dataItem['extend']['qa_data']['task_id'];
                    $msgDes = '悬赏问题已回复';
                    $content = '你好，你的疑惑已给出回复，点击下方即可查看，有什么问题可以追问我继续帮你进行解答～';
                    $btnInfo[] = [
                        'name' => '查看详情',
                        'target' => 'flutter',
                        'link' => "ask_detail?task_id={$taskId}&app_type=" . ($appType === 1 ? 2 : 1),
                        'type' => 6,
                        'id' => $taskId,
                    ];
                    break;
                case 7: // 问答追问问题回复
                    $taskId = $dataItem['extend']['qa_data']['task_id'];
                    $msgDes = '悬赏追问已回复';
                    $content = '你好，你的疑惑已给出回复，点击下方即可查看，有什么问题可以追问我继续帮你进行解答～';
                    $btnInfo[] = [
                        'name' => '查看详情',
                        'target' => 'flutter',
                        'link' => "ask_detail?task_id={$taskId}&app_type=" . ($appType === 1 ? 2 : 1),
                        'type' => 6,
                        'id' => $taskId,
                    ];
                    break;
                case 8: // 发送 档案问题
                    $msgDes = '星盘';
                    $content = '';
                    $recodeExtend = $dataItem['extend']['recode_info'];
                    $ridItem = (int)($recodeExtend['rid'] ?? 0);
                    $list = [
                        "{$recodeExtend['year']}.{$recodeExtend['month']}.{$recodeExtend['day']}",
                        "日{$recodeExtend['sun']} 月{$recodeExtend['moon']} 升{$recodeExtend['asc']}",
                    ];
                    $recodeItem = $recodeModel->getInfoById($ridItem);
                    if ($recodeItem && $recodeItem['status'] == 1)
                    {
                        $target = 'local';
                        $link = "astrolable?rid={$ridItem}&chart=natal&flag=2&data_id={$dataItem['id']}&birtn_year={$recodeExtend['year']}";
                    } else
                    {
                        $target = 'toast';
                        $link = '档案已删除！';
                    }
                    $recodeItemInfo = [
                        'list' => $list,
                        'target' => $target,
                        'link' => $link,
                        'icon' => '/zyhsapp/astro_icon.png',
                    ];
                    break;
                case 9://预约
                    //获取预约状态和预约时间
                    $msgDes = $dataItem['extend']['reservation_info']['title'];
                    $content = $dataItem['extend']['reservation_info']['content'];
                    $statusTmp = (int)$dataItem['extend']['reservation_info']['status'] === 1 ? 1 : 2;
                    $idTmp = (new Zl8UserChatReservationRecord())->where('char_id', $dataItem['id'])->value('id');
                    $appointmentInfo = [
                        'id' => $idTmp ?: 0,
                        'icon' => '/zyhsapp/reservation.png',
                        'status' => $statusTmp,
                        'list' => [
                            '预约时间',
                            $dataItem['extend']['reservation_info']['time_des'],
                        ],
                    ];
                    break;
                case 10:
                    $pluginsInfo = [
                        'icon' => '/test/consult_chat/plugins/gift_icon.png',
                        'list' => ['礼物', '点击打赏'],
                        'target' => 'local',
                        'link' => 'empty',
                    ];
                    $content = '如果你对我的服务满意，可以对我进行打赏，非常感谢！';
                    break;
                case 11:
                    $msgDes = '礼物打赏';
                    $pluginsInfo = [
                        'icon' => '/test/consult_chat/plugins/gift_icon.png',
                        'list' => ['礼物', sprintf('%sx%d | 收益：%s元', $dataItem['extend']['gift_data']['gift_name'], $dataItem['extend']['gift_data']['num'], $dataItem['extend']['gift_data']['earnings'])],
                        'target' => 'local',
                        'link' => 'empty',
                    ];
                    $content = '给你一些奖励';
                    break;
                default:
                    $content = '';
            }
            $data = [
                'id' => $dataItem['id'],
                'type' => $dataItem['type'],
                'time_des' => $createTime,
                'time' => $checkTime,
                'avatar' => $avatar,
                'msg_des' => $msgDes,
                'tags' => $dataItem['extend']['tags'] ?? [],
                'consult_info' => $consultInfo,
                'content' => $content,
                'content_type' => $contentType,
                'btn_info' => $btnInfo ?? null,
                'astr_info' => $recodeItemInfo,
                'appointment_info' => $appointmentInfo ?? null,
                'user_des' => $userDes,
                'server_suc' => $serverSuc,
                'is_comment' => $isComment,
                'plugins_info' => $pluginsInfo ?? null,
            ];
            // 更新最后发送时间
            $lastTime = $dataItem['create_time'];
            $resData[] = $data;
        }

        return $resData;
    }

    /**
     * @param array $ids
     * @param array|null $type
     * @param string $sortType
     * @return array
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        try
        {
            // 获取未删除 的数据
            $data = $this
                ->where(['id' => ['in', $ids]])
                ->column('id,app_type,uid,chat_id,astr_id,type,title,content,data_type,extend,pid,create_time,update_time', 'id');
        }
        catch (\Exception $e)
        {
            $data = [];
        }

        return $data;
    }

    public function batchGetInfoByIds($cids, $field = [])
    {
        $resData = parent::batchGetInfoByIds($cids, $field);

        return $this->dataInit($resData);
    }

    /**
     * 数据初始化
     * @param array $data
     * @return array
     */
    public function dataInit(array $data)
    {
        foreach ($data as $index => $itemData)
        {
            $data[$index] = arrayKeyData2int($itemData, ['id', 'app_type', 'uid', 'chat_id', 'astr_id', 'type', 'data_type', 'pid', 'create_time', 'update_time']);

            if (isset($itemData['extend']))
            {
                $data[$index]['extend'] = $itemData['extend'] ? json_decode($itemData['extend'], true) : [];
            }
        }

        return $data;
    }

    /**
     * 时间转换
     * @param int $time 待转换的时间
     * @param int $now0Time 今日零点时间
     * @return string
     */
    public function timeConvert(int $time, int $now0Time)
    {
        $t = $now0Time - $time;
        if ($t <= 0)
        {
            $timeStr = date('H:i', $time);
        } elseif ($t <= 86400)
        {
            $timeStr = date('昨日 H:i', $time);
        } else
        {
            $timeStr = date('m-d H:i', $time);
        }

        return $timeStr;
    }

    /**
     * 获取 用户 今天发送咨询消息数量
     */
    public function getUserConsultMsgNumByToday(int $appType, $uid)
    {
        $timeDate = date('Ymd');
        return CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel)
            ->setCacheKeyDetail('today_chat_num', "{$timeDate}:{$appType}:{$uid}")
            ->getDataAndSet(function () use ($appType, $uid)
            {
                try
                {
                    $dataList = $this->where(['app_type' => $appType, 'uid' => $uid, 'type' => 2, 'data_type' => ['in', [1, 2]]])->whereTime('create_time', 'today')->group('astr_id')->column('count(astr_id)', 'astr_id');

                    $data = [0 => 0];

                    foreach ($dataList as $astrId => $num)
                    {
                        $data[$astrId] = $num;
                    }

                    return $data;
                }
                catch (\Exception $e)
                {
                    \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
                    $data = [0 => 0];
                }
                return $data;
            }, [], 'today_chat_num');
    }

    /**
     * 用户 发送 咨询师 消息 自增
     * @param int $appType 1=>准有好事 2=>准了APP
     * @param $uid
     * @param $astrId
     * @return void
     * @throws \Exception
     */
    public function setUserConsultMsgAstrNumByTodayInc(int $appType, $uid, $astrId)
    {
        (new ZyhsUserConsultInfo())->updateData($appType, $uid, [
            'num' => $this->raw('num +1'),
        ]);
        $timeDate = date('Ymd');
        CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('today_chat_num', "{$timeDate}:{$appType}:{$uid}")->setCacheInc($astrId, 'today_chat_num');
    }

    /**
     * 获取 用户 今天发送咨询消息数量
     * @param int $appType 1=>准有好事 2=>准了APP
     * @param int $uid
     * @param int $astrId
     * @return array
     */
    public function getUserConsultAstrMsgNumByTodayEx(int $appType, int $uid, int $astrId): array
    {
        $rtcConfig = (new ZyhsConfig())->configInfo('rtc');
        if ($appType === 1)
        {
            $testUser = $rtcConfig['zyhsapp_test_user_id'] ?? '';
        } else
        {
            $testUser = $rtcConfig['zhunleapp_test_user_id'] ?? '';
        }
        $testUidArr = explode(',', $testUser);
        if (in_array($uid, $testUidArr, false))
        {   // 测试 号
            return [
                'total' => 999,  // 今天剩余还能发送咨询问题总数
                'num' => 999,    // 今日 还能 向该占星师发送问题总数
                'max_num' => 999, // 一共还能 咨询问题数
            ];
        } else
        {
            $data = $this->getUserConsultMsgNumByToday($appType, $uid);

            $num = array_sum($data);

            $maxNum = (new ZyhsUserConsultInfo())->getUserMaxSendNum($appType, $uid);

            return [
                'total' => max(15 - $num, 0),  // 今天剩余还能发送咨询问题总数
                'num' => max(5 - ($data[$astrId] ?? 0), 0),    // 今日 还能 向该占星师发送问题总数
                'max_num' => $maxNum, // 一共还能 咨询问题数
            ];
        }
    }

    /**
     * 咨询师 向用户发送咨询消息  【问答功能回复使用】
     */
    public function QuestionAnswerSendConsultMsgToUser(int $appType, int $uid, array $astrInfo, array $data)
    {
        $astrId = $astrInfo['id'];
        $consultChatIdModel = new ZyhsConsultChatRecord();
        $chatId = $consultChatIdModel->getChatIdByAstrId($appType, $uid, $astrId);
        $nowTimw = $data['create_time'];
        if (!$chatId)
        {
            $insertData = [
                'app_type' => $appType,
                'uid' => $uid,
                'astr_id' => $astrId,
                'last_chat_detail_id' => 0,
                'last_chat_detail_time' => 0,
                'create_time' => $nowTimw,
            ];
            // 创建新的会话
            $chatId = $consultChatIdModel->SaveData($insertData);
        }
        // $data = [
        //     'uid' => $uid,
        //     'astr_id' => $astrId,
        //     'type' => 2,    //  1=>APP消息 2=>用户发送消息
        //     'title' => '',
        //     'content' => '', // 提问问题
        //     'data_type' => 6,   // 数据类型  1=>普通消息  2=>图片  3=>语音咨询消息  4=>咨询问题  5=>咨询问题答案 6=>问答悬赏问题回复 7=>问答悬赏追问已回复
        //     'extend' => ['intercept_tips' => ''],  //  语音咨询消息 ｜ 图片信息 | 内容拦截信息
        //     'pid' => 0, // 待更新
        //     'create_time' => $nowTimw,
        // ];
        $data['chat_id'] = $chatId;
        $resData = $this->SaveData($chatId, $data);
        if ($resData)
        {   // 更新用户端 最后咨询信息
            $consultChatIdModel->updateData($chatId, [
                'uid' => $uid,
                'last_chat_detail_id' => $resData['id'],
                'last_chat_detail_time' => $nowTimw,
                'msg_num' => Db::raw('msg_num + 1'),
            ], $appType);
            $consultChatIdModel->setUserUnreadChatIdMsgNum($appType, $uid, $chatId, 1, 1);
            // 更新咨询师端 最后咨询信息  这里使用用户发送更新的方法是因为里面有初始化逻辑
            $zlcr3ConsultChatRecordAstrModel = new ZyhsConsultChatRecordAstr();
            $zlcr3ConsultChatRecordAstrModel->userSendUpdate($appType, $uid, $astrId, [
                'last_chat_detail_id' => $resData['id'],
                'last_chat_detail_time' => $nowTimw,
            ]);
            // 向 用户发送消息
            $userData = current($this->userDataListResert([$resData], $astrInfo, [], $appType));
            $websocketWho = $appType === 1 ? LiveMessage::WHO_TYPE_ZYHS_UID : LiveMessage::WHO_TYPE_UID;
            LiveMessage::sendMsg(LiveMessage::who($websocketWho, 0, $uid), LiveMessage::MSG_TYPE_POP_CONSULT_MSG, [
                'msg_type' => 1,
                'astr_id' => $astrId,
                'msg_data' => $userData,
            ]);

        }
    }

    /**
     * 获取 连线咨询 初始化 档案信息
     * @param int $chatId
     * @return array
     */
    public function getRtcInitRecodeInfo(int $chatId): array
    {
        try
        {
            $beforeTime24 = time() - 86400; // 24小时前的时间戳
            $data = $this->where(['chat_id' => $chatId, 'data_type' => 8, 'create_time' => ['>', $beforeTime24]])->column('extend');
            $resData = [];
            $recodeModel = new ZyhsRecode();
            $utilModel = new Util();
            $rids = [];
            foreach ($data as $dataItem)
            {
                if (empty($dataItem))
                {
                    continue;
                }
                $dataItem = json_decode($dataItem, true);
                $rid = (int)($dataItem['recode_info']['rid'] ?? 0);
                if (!$rid)
                {
                    continue;
                }
                if (in_array($rid, $rids, true))
                {   // 档案已经 处理过了
                    continue;
                }
                $rids[] = $rid; // 标记当前档案ID 已处理
                $recode = $recodeModel->getInfoById($rid);
                if (!$recode || $recode['status'] != 1)
                {
                    continue;
                }
                // 周岁
                $age = Util::getAgeByBirth($recode['year'], $recode['month'], $recode['day'], 2);
                $sex = $sexTxt[$recode['type']] ?? '未知';
                $userDes = '日' . $utilModel->recodeAstroShorthand($recode['sun']) . '月' . $utilModel->recodeAstroShorthand($recode['moon']) . '升' . $utilModel->recodeAstroShorthand($recode['asc']);

                $resData[] = [
                    'rid' => $rid,
                    'name' => $recode['name'],
                    'avatar' => $recode['avatar'],
                    'comments' => $recode['comments'],
                    'user_des' => "{$sex}·{$age}周岁 {$userDes}",
                    'year' => $recode['year'],
                ];
            }

            return $resData;
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return [];
        }
    }

    /**
     * 写入 求礼物信息
     * @param int $chatId
     * @param array $astrInfo
     * @param int $uid
     * @param int $appType 1=>准有好事 2=>准了APP
     * @return void
     */
    public function saveGetGiftData(int $chatId, array $astrInfo, int $uid, int $appType = 1)
    {
        try
        {
            $consultMsgData = [
                'chat_id' => $chatId,
                'app_type' => $appType,
                'uid' => $uid,
                'astr_id' => $astrInfo['id'],
                'type' => 1,    //  1=>APP消息 2=>用户发送消息
                'title' => '',
                'content' => '', // 提问问题
                'data_type' => 10,  // 1=>普通消息  2=>图片  3=>语音咨询消息  4=>咨询问题  5=>咨询问题答案 6=>问答悬赏问题回复 7=>问答悬赏追问已回复 8=>用户发送星盘信息  9=>预约咨询 10=>求打赏礼物 11=>用户打赏礼物
                'extend' => ['intercept_tips' => ''],  //  语音咨询消息 ｜ 图片信息 | 内容拦截信息
                'pid' => 0, // 待更新
                'create_time' => time(),
            ];

            $resData = $this->SaveData($chatId, $consultMsgData);
            $websocketWho = $appType === 1 ? LiveMessage::WHO_TYPE_ZYHS_UID : LiveMessage::WHO_TYPE_UID;
            // 向用户 发送消息
            $msgData1 = [
                'id' => $resData['id'],
                'type' => 2,
                'time_des' => '',
                'time' => '',
                'avatar' => $astrInfo['avatar'],
                'msg_des' => '',
                'tags' => [],
                'consult_info' => null,
                'btn_info' => null,
                'content' => '如果你对我的服务满意，可以对我进行打赏，非常感谢！',
                'content_type' => 1,
                'astr_info' => null,
                'appointment_info' => null,
                'plugins_info' => [
                    'icon' => '/test/consult_chat/plugins/gift_icon.png',
                    'list' => ['礼物', '点击打赏'],
                    'target' => 'local',
                    'link' => 'consult_pop_gift?need_auth=2',
                ],
            ];
            LiveMessage::sendMsg(LiveMessage::who($websocketWho, 0, $uid), LiveMessage::MSG_TYPE_POP_CONSULT_MSG, [
                'msg_type' => 1,
                'astr_id' => $astrInfo['id'],
                'msg_data' => $msgData1,
            ]);
            // 向咨询师 发送消息
            $msgData2 = [
                'id' => $resData['id'],
                'type' => 1,
                'time_des' => '',
                'time' => '',
                'avatar' => $astrInfo['avatar'],
                'msg_des' => '',
                'tags' => [],
                'consult_info' => null,
                'btn_info' => null,
                'content' => '如果你对我的服务满意，可以对我进行打赏，非常感谢！',
                'content_type' => 1,
                'astr_info' => null,
                'appointment_info' => null,
                'plugins_info' => [
                    'icon' => '/test/consult_chat/plugins/gift_icon.png',
                    'list' => ['礼物', '点击打赏'],
                    'target' => 'local',
                    'link' => 'empty',
                ],
            ];
            // 判断咨询师是否在线
            LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_ASTRO, 0, $astrInfo['id']), LiveMessage::MSG_TYPE_POP_CONSULT_MSG, [
                'msg_type' => 1,
                'app_type' => $appType,
                'uid' => $uid,
                'msg_data' => $msgData2,
            ]);
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()发送 求打赏消息异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
        }
    }
}
